package com.my.socket.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.FutureTask;

/**
 * User: Alex Zhong
 * Date: 2016/6/17
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(9999));

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        LOGGER.info("waiting for the client connection at {}", serverSocketChannel.getLocalAddress());

        SelectCallable selectCallable = new SelectCallable(selector);
        FutureTask futureTask = new FutureTask(selectCallable);
        Thread thread = new Thread(futureTask);
        thread.start();

//        selector.close();
//        serverSocketChannel.close();
    }
}
